<template>
  <div>
    <top-steps
      :state-steps="stateSteps"
      :active-state="activeState"
      @changeState="changeState"
    />
    <div class="topSearch">
      <div>
        <el-input
          v-model="searchCriteria.name"
          maxlength="50"
          clearable
          placeholder="title"
        />
        <el-input
          v-model="searchCriteria.sku"
          maxlength="50"
          clearable
          placeholder="sku"
        />
        <el-select
          v-model="searchCriteria.storeId"
          placeholder="Choose Store"
          @change="initParams"
        >
          <el-option label="all" :value="0" />
          <el-option
            v-for="item in storeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-if="searchCriteria.storeId > 0"
          v-model="searchCriteria.categoryId"
          placeholder="category"
          @visible-change="getCategory"
        >
          <el-option
            v-for="item in searchCategoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-date-picker
          v-model="searchDate"
          class="myDatePicker"
          type="daterange"
          range-separator="to"
          start-placeholder="Start Date"
          end-placeholder="End Date"
          value-format="yyyy-MM-dd"
        />
        <el-button type="primary" @click="searchData()">Search</el-button>
      </div>
      <sticky :z-index="8" :sticky-top="50">
        <div class="topBtn">
          <template v-if="activeState !== '1'">
            <el-button
              v-preventReClick
              type="primary"
              @click="productPush('more')"
            >
              Push
            </el-button>
          </template>
          <template v-if="activeState === '1'">
            <el-dropdown type="primary" @command="productPull">
              <el-button type="primary">
                Pull<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(item, index) in storeOptions"
                  :key="index"
                  :command="item.id"
                >{{ item.name }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="primary" @click="batchPull">
              Batch Pull
            </el-button>
            <el-button type="primary" @click="goToLog">Task Log</el-button>
            <el-button
              v-preventReClick
              type="primary"
              icon="el-icon-upload2"
              @click="productPublish('more')"
            >Publish</el-button>
            <el-button
              v-preventReClick
              type="primary"
              icon="el-icon-download"
              @click="productUnPublish('more')"
            >Unpublish</el-button>
          </template>
        </div>
      </sticky>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="Image" width="100">
        <template slot-scope="scope">
          <el-image
            class="productImg"
            lazy
            :src="
              scope.row.images.length > 0
                ? scope.row.images[0].uri.indexOf('http') === 0
                  ? scope.row.images[0].uri
                  : imgPrefix + scope.row.images[0].uri + imgSuffix
                : ''
            "
            @click="toProview(scope.row.images[0].uri.indexOf('http') === 0 ? scope.row.images[0].uri : imgPrefix + scope.row.images[0].uri)"
          >
            <div slot="placeholder" class="image-slot">
              <i class="el-icon-loading" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="product.storeName" label="Store" width="120" />
      <el-table-column label="Title">
        <template slot-scope="scope">
          <div class="ProductTitle">{{ scope.row.product.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="product.sku" label="Sku" />
      <el-table-column label="Category">
        <template slot-scope="scope">
          <el-tag
            v-for="(item, index) in scope.row.categories"
            :key="index"
            type="info"
            style="margin-bottom:5px;margin-right:5px"
          >
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.product.isSale === 0">Offline</el-tag>
          <el-tag
            v-if="scope.row.product.isSale === 1"
            type="primary"
          >Online</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="product.createTime" label="Create Time" />
      <el-table-column fixed="right" label="Operation" width="130">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              @click="goDetail(scope.row.product.storeId, scope.row.product.id)"
            >Edit</el-button>
            <el-button
              type="text"
              @click="deleteItem(scope.row.product.id)"
            >Delete</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 图片预览 -->
    <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />

    <!-- 选择商店的弹框 -->
    <template>
      <el-dialog
        title="choose a store"
        append-to-body
        width="20%"
        :visible.sync="claimVisible"
        @close="closeCalim"
      >
        <el-form :model="form">
          <el-form-item label="choose store" label-width="100px">
            <el-select v-model="form.storeId" placeholder="please choose store">
              <el-option
                v-for="(item, index) in storeOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeCalim">cancel</el-button>
          <el-button type="primary" @click="submitData">sure</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import {
  productShopifyPage,
  productWoocPage,
  productShopifyDelete,
  productCategoryList,
  productShopifyPublish,
  productShopifyUnpublish,
  productWoocPublish,
  productWoocUnpublish
} from '@/api/product';
import { storePush } from '@/api/common';
import {
  productPull,
  batchPull,
  productPush,
  authorizedList
} from '@/api/authorized';
import Sticky from '@/components/Sticky';
import ProviewImg from '@/components/Proview/proviewImg';
import TopSteps from './topSteps';
import { postResult } from '@/utils/dataFormat';
import { jointOrderIds } from '@/utils/orderUtils';
export default {
  components: {
    ProviewImg,
    Sticky,
    TopSteps
  },
  props: {
    pageName: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      stateSteps: [
        { name: 'Drafts', pathName: '0' },
        { name: 'Success', pathName: '1' },
        { name: 'Failed', pathName: '2' }
      ],
      activeState: '0',
      proviewUrl: '',
      searchCriteria: {},
      searchDate: '',
      tableData: [],
      loading: false,
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      productId: 0,
      searchCategoryOptions: [],
      storeOptions: [],
      claimDisabled: true,
      claimVisible: false,
      SelectArr: [],
      form: {
        storeId: ''
      }
    };
  },
  computed: {
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  watch: {
    pageName(newV, oldV) {
      this.init(1);
    }
  },
  mounted() {
    this.activeState = this.$route.params.state
      ? this.$route.params.state
      : '0';
    authorizedList({
      storeType: this.pageName
    }).then((res) => {
      this.storeOptions = res.data;
      this.$set(
        this.searchCriteria,
        'storeId',
        this.$route.params.storeId || null
      );
      this.init();
    });
  },
  methods: {
    init() {
      this.loading = true;
      const params = {
        ...this.searchCriteria,
        beginDate: this.searchDate ? this.searchDate[0] : '',
        endDate: this.searchDate ? this.searchDate[1] : '',
        pushStatus: ~~this.activeState,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      };
      var httpPage = null;
      if (this.pageName === 'SHOPIFY') {
        httpPage = productShopifyPage(params);
      } else if (this.pageName === 'WOOCOMMERCE') {
        httpPage = productWoocPage(params);
      }
      httpPage.then((res) => {
        this.loading = false;
        if (res.code === 200) {
          // res.data.data.forEach(item => {
          //   item['img'] = item.
          // })
          this.tableData = res.data.data;
          this.total = res.data.totalCount;
        }
      });
    },
    changeState(val) {
      this.activeState = val;
      this.init();
    },
    getStoreData() {
      authorizedList({
        storeType: this.pageName === 'WOOCOMMERCE' ? 'WOOCOMMERCE' : 'SHOPIFY'
      }).then((res) => {
        this.storeOptions = res.data;
      });
    },
    searchData() {
      this.init();
    },
    goToLog() {
      const { href } = this.$router.resolve({
        name: 'TaskLog',
        params: { key: 'PRODUCT' }
      });
      window.open(href, '_blank');
    },
    productPush(type, id) {
      // 发布商品
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      productPush({ productIds: ids }).then((res) => {
        postResult(res, this.$message, this.init);
      });
    },
    productPull(id) {
      // 拉取商品
      productPull([id]).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    batchPull() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('Please select at least one option');
      }
      const productIds = this.multipleSelection.map((item) => item.product.id);
      batchPull({ productIds }).then((res) => {
        postResult(res, this.$message);
      });
    },
    productPublish(type, id) {
      // 上架
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      if (this.pageName === 'SHOPIFY') {
        productShopifyPublish(ids).then((res) => {
          postResult(res, this.$message, this.init);
        });
      } else if (this.pageName === 'WOOCOMMERCE') {
        productWoocPublish(ids).then((res) => {
          postResult(res, this.$message, this.init);
        });
      }
    },
    productUnPublish(type, id) {
      // 下架
      const ids = jointOrderIds(
        type,
        id,
        this.multipleSelection,
        this.$message
      );
      if (!ids) return;
      if (this.pageName === 'SHOPIFY') {
        productShopifyUnpublish(ids).then((res) => {
          postResult(res, this.$message, this.init);
        });
      } else if (this.pageName === 'WOOCOMMERCE') {
        productWoocUnpublish(ids).then((res) => {
          postResult(res, this.$message, this.init);
        });
      }
    },
    getCategory(val) {
      if (!val) return;
      productCategoryList({
        storeId: this.searchCriteria.storeId,
        parentId: 0
      }).then((res) => {
        // 分类
        this.searchCategoryOptions = JSON.parse(JSON.stringify(res.data));
        this.searchCategoryOptions.unshift({ id: 0, name: 'All' });
      });
    },
    initParams(val) {
      if (val === 0 && this.searchCriteria.categoryId) {
        delete this.searchCriteria.categoryId;
      }
    },
    exportProduct() {
      // 导出商品至店铺
    },
    goDetail(storeId, productId) {
      let name = '';
      if (this.pageName === 'SHOPIFY') {
        name = 'ShopifyDet';
      } else if (this.pageName === 'WOOCOMMERCE') {
        name = 'WoocDet';
      }
      this.$router.push({
        name,
        params: {
          storeId,
          productId
        }
      });
    },
    deleteItem(id) {
      this.$confirm(
        'his action will permanently delete the item. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'Hint'
        }
      )
        .then(() => {
          productShopifyDelete([id]).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {
          this.$message.info('undeleted');
        });
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    handleSelectionChange(val) {
      if (val.length) {
        this.claimDisabled = false;
      } else {
        this.claimDisabled = true;
      }
      this.SelectArr = val;
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    },
    closeClaim() {
      this.claimVisible = true;
    },
    closeCalim() {
      this.claimVisible = false;
    },
    submitData() {
      const ids = [];
      this.claimVisible = false;
      for (var i = 0; i < this.SelectArr.length; i++) {
        ids.push(this.SelectArr[i].id);
      }
      const params = {
        productIds: ids,
        storeId: this.form.storeId
      };
      storePush(params).then((res) => {
        if (res.code === 200) {
          this.$message.success('success claim to store');
        }
      });
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
.topBtn {
  padding: 10px 0;
  background: #fff;
  .el-button + .el-button {
    margin-left: 0;
  }
}

.el-dropdown-menu {
  min-width: 100px;
}

.ProductTitle {
  line-height: 17px;
}
::v-deep .el-tag {
  height: auto;
  white-space: inherit;
  line-height: 17px;
}
</style>
